import { DictionaryType, requestDict, allDataCategory } from "../../../common/dictionary/dictionary-type.js";
import tablemgtentryApi from '../../../common/api/ctn/auditmain.api.js'
import { uploadFile, requestFilePath, publicFileDraw, sliceFileName } from "../../../common/api/file-request.js";
import doT from '../../../../vendor/template/doT.js';
import { Select2Page } from "../../../common/serve-request.js";


(function (window, document, $) {
    let _vm, getReceveEntry = [];
    let auditItemList = [];// 审查项列表
    let rectifyOptions = [];
    let prodSafeCategoryList =[];
    // 生产安全类别和检查项目的对应关系
    let inspectProject = {};
    // 生产安全类别选择框的数据
    let sdata = [];

    $(function () {
        _vm = new Vue({
            el: "#recevEntries-form",
            data() {
                return {
                    entries: [{
                        "auditItemId": "",
                        "textt": "",
                        "text": "",
                        "weight": "",
                        "prodSafeCategory": '',
                        "prodSafeCategoryName": '',
                        "inspectProject": '',
                        "inspectProjectName": '',
                        "deduct": "",
                        "reason": "",
                        "suggestion": "",
                        "principalIds": "",
                        "principal": "",
                        "timeLimit": "",
                        "result": "",
                        "resultName": "",
                        "imageList": [],
                        "image": "",
                        "isQualified": false,
                        "isRectify": '',
                        "uploadCount": 0,
                    }],
                }
            },
            mounted() {
                let url = location.href
                let params = {} // url参数
                for (let key of (new URL(url)).searchParams.entries()) {
                    key[1] ? params[key[0]] = key[1] : ''
                }
                if (params.isEdit == 'true') {
                    document.title = '入圈登记收货分录 - 编辑'
                }
            },
            methods: {
                // 保存
                submit() {
                    let { auditItemId, weight, deduct, reason, suggestion, principal, timeLimit, result } = _vm.entries[0]
                    if (!Utils.IsNotNull(auditItemId)) {
                        return $.toptip(`请选择审查内容!`, 'warning');
                    }
                    if (!Utils.IsNotNull(deduct)) {
                        return $.toptip(`请输入扣分!`, 'warning');
                    }
                    if (!(/^\d+$/).test(deduct)) {
                        return $.toptip(`扣分为非负整数!`, 'warning');
                    }
                    if (Number(deduct) > Number(weight)) {
                        return $.toptip(`扣分不能大于权重分!`, 'warning');
                    }
                    if (!Utils.IsNotNull(reason)) {
                        return $.toptip(`请输入扣分原因!`, 'warning');
                    }
                    if (!Utils.IsNotNull(suggestion)) {
                        return $.toptip(`请输入整改建议!`, 'warning');
                    }
                    if (!Utils.IsNotNull(principal)) {
                        return $.toptip(`请选择负责人!`, 'warning');
                    }
                    if (!Utils.IsNotNull(timeLimit)) {
                        return $.toptip(`请选择期限日期!`, 'warning');
                    }
                    if (!Utils.IsNotNull(timeLimit)) {
                        return $.toptip(`请选择整改情况!`, 'result');
                    }
                    
                    let imageId='';
                    _vm.entries[0].imageList.forEach((itm)=>{
                        imageId += ','+itm.imageId;
                    })
                    _vm.entries[0].image = imageId.substring(1, imageId.length);
                    savetips({ ..._vm.entries[0] })
                }
            }
        });
        $(document).on('mousedown', '.clearContent', function (e) {
            e.target.style.fontSize = '16px';
        });
        $(document).on('focus', '.clearContent', function (e) {
            e.target.style.fontSize = '16px';
        });
        $('body').attr('data-weui-theme', 'light'); //强制光明模式
        _initCommand();
        uploadInit();


    });

    // 初始化数据
    const _initCommand = async () => {
        getReceveEntry = JSON.parse(Utils.GetSessionStorage("getReceveEntry")) || [];
        auditItemList = JSON.parse(Utils.GetSessionStorage("auditItemList")) || [];
        let isEdit = JSON.parse(getUrlKey('isEdit'))
        let seqId = getUrlKey('index')

        // 生产安全类别选择框的数据
        let sdata = []
        // 生产安全类别
        await requestDict(DictionaryType.PRODSAFE_CATEGORY).then(res => {
            prodSafeCategoryList = res.data.concat([]);
            sdata = [];
            res.data.forEach((item)=>{
                sdata.push({
                    id: item.value,
                    text: item.displayName
                })
            })
            $('#prodSafeCategory').empty().select2({
                placeholder: '请选择生产安全类别...', //默认文字提示
                language: "zh-CN",//汉化
                allowClear: true,//允许清空
                data: res.data.map(item => {
                    return { ...item, id: item.value, text: item.displayName }
                })
            });
            $('#prodSafeCategory').setSelectValue();
        })
        
        let data = await Promise.all(sdata.map(item => {
            return requestDict(item.id)
        }))
        data.forEach((item, index) => {
            if (item.data.length !== 0) {
                // 管理序列：[]    这里分类数据字典字典值内容
                inspectProject[sdata[index]['id']] = item.data
            }
        })

        // 生产安全类别
        $(`#prodSafeCategory`).empty().select2({
            placeholder: '请选择生产安全类别...', //默认文字提示
            language: "zh-CN",//汉化
            allowClear: true,//允许清空
            data: sdata
        });
        $(`#prodSafeCategory`).setSelectValue();

        // 选择生产安全类别
        $(`#prodSafeCategory`).on('select2:select', function (e) {
            let id = $(this).select2('data')[0]?.id;
            let name = $(this).select2('data')[0]?.text;
            _vm.entries[0].prodSafeCategory = id || '';
            _vm.entries[0].prodSafeCategoryName = name || '';
            let data1 = inspectProject[id]||[];
            getinspectproject( `inspectProject`,data1);
            var data = e.params.data; // 获取选中项的数据
            var text = data.text; // 获取选中项的文本
            var saleOrgsinfo = cutstr(text, 20); // 截取字符串
            $(this).select2('val', data.id); // 假设您想根据ID设置选中值
            $(this).next('.select2-container').find('.select2-selection__rendered').text(saleOrgsinfo);
        })

        // 选择检查项目
        $(`#inspectProject`).on('select2:select', function (e) {
            let id = $(this).select2('data')[0]?.id;
            let name = $(this).select2('data')[0]?.text;
            _vm.entries[0].inspectProject = id || '';
            _vm.entries[0].inspectProjectName = name || '';
            var data = e.params.data; // 获取选中项的数据
            var text = data.text; // 获取选中项的文本
            var saleOrgsinfo = cutstr(text, 20); // 截取字符串
            $(this).select2('val', data.id); // 假设您想根据ID设置选中值
            $(this).next('.select2-container').find('.select2-selection__rendered').text(saleOrgsinfo);
        })

        //审查项列表
        $(`#auditItemId`).empty().select2({
            placeholder: '请选择审查内容...',//默认文字提示
            language: "zh-CN",//汉化
            language: {
                noResults: () => {
                    return noResultsStr
                }
            },
            allowClear: true,//允许清空
            width: '100%',
            data: auditItemList,
        });
        $('#auditItemId').setSelectValue();

        // 选择审查项
        $('#auditItemId').on('select2:select', function (e) {
            let res = e.params?.data || '';
            $(`#prodSafeCategory`).val(res?.prodSafeCategory || '').trigger("change");
            let inspectProjectObj = {id: res?.inspectProject, name: res?.inspectProjectName}
            getinspectproject(`inspectProject`, inspectProject[res?.prodSafeCategory]||[], inspectProjectObj || '')
            _vm.entries[0].auditItemId = res?.id || '';
            _vm.entries[0].textt = res?.text || '';
            _vm.entries[0].weight = res?.weight || '';
            _vm.entries[0].prodSafeCategory = res?.prodSafeCategory || '';
            _vm.entries[0].prodSafeCategoryName = res?.prodSafeCategoryName || '';
            _vm.entries[0].inspectProject = res?.inspectProject || '';
            _vm.entries[0].inspectProjectName = res?.inspectProjectName || '';
            var data = e.params.data; // 获取选中项的数据
            var text = data.text; // 获取选中项的文本
            var saleOrgsinfo = cutstr(text, 20); // 截取字符串
            $(this).select2('val', data.id); // 假设您想根据ID设置选中值
            $(this).next('.select2-container').find('.select2-selection__rendered').text(saleOrgsinfo);
        });
        setIsRectify();
        function setIsRectify(){
            $(`#isRectify`).empty().select2({
                placeholder: '请选择是否整改...', //默认文字提示
                language: "zh-CN", //汉化
                allowClear: true, //允许清空
                data: [{id: true,text: `是`},{id: false,text: `否`, selected: true}]
            });
        } 

        $(`#isRectify`).on('select2:select', function (e) {
            _vm.entries[0].isRectify = $(this).val();
        });

        // 获取整改情况数据字典
        await requestDict(DictionaryType.RESULT_TYPE).then(res => {
            rectifyOptions = res.data.map(item => {
                return {
                    id: item.value,
                    text: item.displayName
                }
            })
            $(`#result`).select2({
                placeholder: '请选择整改情况...', //默认文字提示
                language: "zh-CN",//汉化
                allowClear: true,//允许清空
                width: '100%',
                data: rectifyOptions
            })
            $('#result').setSelectValue()
        })

        $(`#result`).on('select2:select', function (e) {
            _vm.entries[0].result = $(this).val();
            _vm.entries[0].resultName = $(this).select2('data')[0]?.text;
            let data = e.params.data; // 获取选中项的数据
            let text = data.text; // 获取选中项的文本
            let saleOrgsinfo = cutstr(text, 20); // 截取字符串
            $(this).select2('val', data.id); // 假设您想根据ID设置选中值
            $(this).next('.select2-container').find('.select2-selection__rendered').text(saleOrgsinfo);
        });

        // 负责人
        $(`#principalIds`).select2({
            language: "zh-CN",
            allowClear: true,//允许清空
            placeholder: '请选择人员...', //默认文字提示
            multiple: true, //是否多选
            ajax: {
                url: Utils.CurDomain.EmployeeMgtUrl + `/emplrecds/by/q`,
                dataType: 'json',
                type: 'GET',
                beforeSend: Utils.AjaxBeforeSend,
                data: function (params) {
                    return {
                        Status: true,
                        // SearchInfo: params.term,
                        PageSize: 10,
                        PageIndex: (params.page || 1) - 1,
                        ...(Utils.IsNotNull(params.term) ? { SearchInfo: params.term } : {})
                    };
                },
                cache: true,
                delay: 700,//等待用户输入完后的 在等700毫秒 进行搜索
                //minimumInputLength: 1, // 只有当输入长度大于或等于1时，才会触发搜索
                processResults: function (data, params) {
                    params.page = params.page || 1;
                    let _data = data.data.items.map(item => {
                        item.id = item.id;
                        item.text = `${item.name}`;
                        return item;
                    });
                    return {
                        results: _data,// 后台返回的数据集
                        pagination: {
                            more: params.page < data.data.totalPages// 总页数为10，那么1-9页的时候都可以下拉刷新
                        }
                    };
                },
                error: Utils.AjaxError
                //minimumInputLength: 1,
            }
        });
        $('#principalIds').setSelectValue();
        $(`#principalIds`).on("select2:select", function (e) {
            let _ids = [], _names = [];
            let list = $(this).select2('data');
            for (let i = 0; i < list.length; i++) {
                _ids.push(list[i]?.id);
                _names.push(list[i]?.text);
            }
            $(`#principal`).val(_names.join(","));
            _vm.entries[0].principalIds = _ids.join(",");
            _vm.entries[0].principal = $('#principal').val();
        });

        // 编辑时赋值 66
        if (isEdit) {
            let datas = getReceveEntry.find(item => item.seq == seqId)
            const propertiesToCopy = [
                "auditItemId","textt","text","weight","prodSafeCategory",
                "prodSafeCategoryName","inspectProject","inspectProjectName",
                "deduct","reason","suggestion","principalIds",
                "principal","timeLimit","result","resultName",
                "imageList","image","isQualified","isRectify",
            ];
            propertiesToCopy.reduce((obj, prop) => {
                _vm.entries[0][prop] = datas[prop];
            }, {});
            let textt = cutstr(_vm.entries[0].textt, 20);
            $(`#auditItemId`).select2('val', _vm.entries[0].auditItemId); // 假设您想根据ID设置选中值
            $(`#auditItemId`).next('.select2-container').find('.select2-selection__rendered').text(textt);
            $(`#prodSafeCategory`).setSelectValue(_vm.entries[0].prodSafeCategory, cutstr(_vm.entries[0].prodSafeCategoryName, 20));
            let inspectProjectObj = {id: _vm.entries[0]?.inspectProject, name: _vm.entries[0]?.inspectProjectName}
            getinspectproject(`inspectProject`, inspectProject[_vm.entries[0]?.prodSafeCategory]||[], inspectProjectObj||'')
            $(`#isRectify`).val(_vm.entries[0].isRectify);
            if (_vm.entries[0].principalIds.indexOf(',') == -1) {
                $(`#principalIds`).setSelectValue(_vm.entries[0].principalIds, _vm.entries[0].principal)
            } else {
                $(`#principalIds`).setSelectValue(_vm.entries[0].principalIds.split(','), _vm.entries[0].principal.split(','));
            }
            $(`#result`).setSelectValue(_vm.entries[0].result, cutstr(_vm.entries[0].resultName, 20));
            _images(_vm.entries[0].image.split(','));
        }

        //取消按钮，返回列表
        $(document).on('click', '#returnMain', function () {
            location.href = `../prodsafetymgt/addtablemgts.html?v=${Utils.GetTime()}`;
        });

        // 选择评分日期
        $('#timeLimit-date').on('click', function () {
            picktimeLimit();
        });

    }

    // 日期选择器
    const picktimeLimit = () => {
        weui.datePicker({
            defaultValue: (moment(new Date()).format('YYYY-MM-DD')).split('-'),
            // end: moment(new Date()).format('YYYY-MM-DD'),
            className: 'mypick',
            onConfirm: async function (result) {
                let value = `${result[0].value}-${result[1].value}-${result[2].value}`;
                _vm.entries[0].timeLimit = moment(new Date(value)).format('YYYY-MM-DD')
            }
        });
    }

    // 保存提示
    const savetips = (data) => {
        let savetype
        if (Utils.IsNotNull(getUrlKey("isEdit"))) {
            savetype = '修改'
        }
        else {
            savetype = '保存'
        }

        $.modal({
            autoClose: false,
            title: '提示',
            text: `<div class="weui-cells__group weui-cells__group_form" style="margin-top:-5px">
    				<div class="" style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;">
    					<div>是否确认${savetype}该分录？</div>
    				</div>`,
            buttons: [
                {
                    text: "取消", className: "default", onClick: function () {
                        $.closeModal();
                    }
                },
                {
                    text: "保存", onClick: function () {
                        let seq = parseInt(getUrlKey('index'))
                        let isEdit = JSON.parse(getUrlKey('isEdit'))
                        // 新增
                        if (!isEdit) {
                            getReceveEntry.push(data)
                        }
                        // 编辑
                        else if (isEdit) {
                            getReceveEntry[seq] = data
                        }
                        getReceveEntry.map((item, index) => {
                            item.seq = index
                        })
                        // 存入SessionStorage
                        JSON.stringify(Utils.SetSessionStorage("getReceveEntry", getReceveEntry))
                        location.href = `./addtablemgts.html?v=${Utils.GetTime()}`;
                        $.closeModal();
                    }
                }
            ]
        });
    }

    // 获取地址栏的参数
    const getUrlKey = (name) => {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    }
    //解决字段过长问题
    const cutstr = (str, len) => {
        var str_length = 0;
        var str_len = 0;
        var str_cut = new String();
        str_len = str.length;
        for (var i = 0; i < str_len; i++) {
            var a = str.charAt(i);
            str_length++;
            if (escape(a).length > 4) {
                //中文字符的长度经编码之后大于4 
                str_length++;
            }
            str_cut = str_cut.concat(a);
            if (str_length >= len) {
                str_cut = str_cut.concat("...");
                return str_cut;
            }
        }
        //如果给定字符串小于指定长度，则返回源字符串； 
        if (str_length < len) {
            return str;
        }
    }

    function unique(arr) {
        const res = new Map();
        return JSON.parse(JSON.stringify(arr)).filter((a) => !res.has(a.id) && res.set(a.id, 1))
    }

    // 获取检查项目
    const getinspectproject = (id, res, json) => {
        $(`#${id}`).attr('disabled',false);
        $(`#${id}`).empty().select2({
            placeholder: '请选择检查项目...', //默认文字提示
            language: "zh-CN",//汉化
            allowClear: true,//允许清空
            data: res.map(item => {
                return {
                    id: item.value,
                    text: item.displayName
                }
            }),
        });
        $(`#${id}`).setSelectValue();
        if (json) {
            let name = cutstr(json.name, 20); // 截取字符串
            $(`#${id}`).setSelectValue(json.id, name);
        }
    }

    // 附件上传
    const uploadInit = () => {
        weui.uploader('#uploader', {
            url: '',
            auto: false,
            type: 'file',
            compress: { isNoTCompress: true },
            onBeforeQueued: function (files) {
                if (!isMobile() && files.length > 0) {
                    $.toptip('请使用手机拍照上传！', 'warning');
                    return false;
                }
                if (["image/jpg", "image/jpeg", "image/png"].indexOf(this.type) < 0) {
                    $.toptip('请上传图片', 'warning');
                    return false; // 阻止文件添加
                }
                $.showLoading('上传中..');
                _vm.entries[0].uploadCount = ++_vm.entries[0].uploadCount;
                if (_vm.entries[0].uploadCount == 3) {
                    $('.weui-uploader__input-box').hide();
                }
            },
            onQueued: async function () {
                const file = this;
                let suffix = this.name.split('.').pop().toLowerCase(); //截取附件后缀
                let name = this.name.slice(0, 11 - (suffix.length) - 1); //计算截取文件的11位字符
                let newName = name + '.' + suffix
                let file1 = publicFileDraw(newName, _vm);
                // 在这里添加日期和地点水印
                const currentDate = moment(new Date()).format('YYYY-MM-DD')
                const currentTime = moment(new Date()).format('HH:mm:ss')
                const locationWatermark = $('#addressInfo').text()
                const canvas = document.createElement('canvas');
                const context = canvas.getContext('2d');
                const image = new Image();
                image.src = window.URL.createObjectURL(file);

                if (!Utils.IsNotNull(locationWatermark)) {
                    $.toptip('定位失败!', 'warning');
                    $.hideLoading();
                    $('#uploaderFiles').last().empty()
                    return
                }
                image.onload = function () {
                    canvas.width = image.width;
                    canvas.height = image.height;
                    // 在canvas上绘制原始图片
                    context.drawImage(image, 0, 0);

                    // 添加水印，支持换行
                    const watermarkText = currentDate + ' ' + currentTime + '\n' + locationWatermark;
                    context.font = '700 ' + 80 + 'px Arial';
                    context.fillStyle = 'white';

                    // 在指定位置绘制文本
                    const x = 10;
                    const y = image.height - 160;
                    drawWrappedText(context, watermarkText, x, y, 200, 130);  // 调用自定义函数

                    // 将canvas转为Blob
                    canvas.toBlob(function (blob) {
                        const formData = new FormData();
                        formData.append('apiobjfile', blob, file1);
                        _uploadFileDraw(formData, file, _vm);
                    }, file.type || 'image/png');  // 使用原始图片的类型或默认为PNG
                }
            }
        });
        $('#uploaderFiles').click(function (e) {
            let target = e.target;
            while (!target.classList.contains('weui-uploader__file') && target) {
                target = target.parentNode;
            }
            if (!target) return;
            //从图片对应的li标签中获得所需属性
            let gallery = weui.gallery($(target).attr('data-url'), {
                className: 'custom-name',
                onDelete: function () {
                    //删除图片的回调
                    $.confirm({
                        title: '删除提示',
                        text: '确定删除该图片？',
                        onOK: function () {
                            let _id = $(target).attr('data-id');
                            _vm.entries[0].imageList = _vm.entries[0].imageList.filter(item => item.id != _id);
                            _vm.entries[0].uploadCount = --_vm.entries[0].uploadCount;
                            target.remove();
                            gallery.hide();
                            // 添加3张后隐藏上传按钮
                            if (_vm.entries[0].uploadCount == 3) {
                                $(".weui-uploader__input-box").hide();
                            } else {
                                $(".weui-uploader__input-box").show();
                            }
                        },
                        onCancel: function () {
                        }
                    });
                }
            });
        });
    }
    // 自定义函数，用于在Canvas上绘制换行的文本
    function drawWrappedText(context, text, x, y, maxWidth, lineHeight) {
        var words = text.split('\n');
        var line = '';
        var yOffset = 0;

        for (var i = 0; i < words.length; i++) {
            var word = words[i];
            var testLine = line + word + ' ';
            var metrics = context.measureText(testLine);
            var testWidth = metrics.width;

            if (testWidth > maxWidth && i > 0) {
                context.fillText(line, x, y + yOffset);
                line = word + ' ';
                yOffset += lineHeight;
            } else {
                line = testLine;
            }
        }

        context.fillText(line, x, y + yOffset);
    }
    function isMobile() {
        return /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
    }
    // 附件上传
    const _uploadFileDraw = (formFile, upFiles, _vm, newName) => {
        uploadFile(formFile).then(async res => {
            if (res.isSucceed) {
                let imageurl = await requestFilePath(res.data)
                let _list = _vm.entries[0].imageList;
                _list.push({
                    id: $("#uploaderFiles li").length,
                    imageId: res.data,
                    url: imageurl.data,
                });
                _vm.entries[0].imageList = _list;
                $("#uploaderFiles li").each(function (i) {
                    $(this).attr('data-id', _vm.entries[0].imageList[i].id);
                    $(this).attr('data-image-id', _vm.entries[0].imageList[i].imageId);
                    $(this).attr('data-url', _vm.entries[0].imageList[i].url);
                    $(this).css({ 'background-image': `url(${_vm.entries[0].imageList[i].url})` });
                });
                $('.weui-uploader__file-content').hide();
                $('.weui-uploader__file').removeClass('weui-uploader__file_status');
            }
        }).catch(res => {
            $("#uploaderFiles li").eq($("#uploaderFiles li").length - 1).remove();
            _vm.entries[0].uploadCount = --_vm.entries[0].uploadCount;
            $.toptip(res.msg, 'error');
        }).finally(_ => {
            $.hideLoading();
            $.closeModal();
        });
    }
    // 编辑回显
    const _images = async (file) => {
        _vm.entries[0].imageList=[];
        let _imag = file;
        if (_imag) {
            let _sun = 0;
            for (let i = 0; i < _imag.length; i++) {
                ++_sun;
                await requestFilePath(_imag[i]).then(_res => {
                    _vm.entries[0].imageList.push({
                        id: _sun,
                        url: _res.data,
                        imageId: _imag[i],
                    });
                    if (_res.isSucceed) {
                        let _li;
                        _li = `<li class="weui-uploader__file" data-id="${_sun}" data-url="${_res.data}" data-image-id="${_imag[i]}" style="background-image: url(${_res.data}) "></li>`;
                        $('#uploaderFiles').append(_li);
                    }
                });
            }
            if (_sun == 3) {
                $(".weui-uploader__input-box").hide();
            }
            _vm.entries[0].uploadCount = _sun;
        }
    }


})(window, document, jQuery)